<?php

namespace app\api\controller;

use app\admin\model\Article;
use app\admin\model\Bank;
use app\admin\model\BankCard;
use app\admin\model\Banner;
use app\admin\model\BatteryType;
use app\admin\model\BillOrder;
use app\admin\model\Car as CarModel;
use app\admin\model\CarBrand;
use app\admin\model\CarColor;
use app\admin\model\CarLocation;
use app\admin\model\ChargePile;
use app\admin\model\ElectricDegrees;
use app\admin\model\HiddenDanger;
use app\admin\model\Kind;
use app\admin\model\Manufacturer;
use app\admin\model\Operator;
use app\admin\model\UserMessage;
use app\admin\model\wraning\WarningFacility;
use app\admin\model\wraning\WarningLog;
use app\common\controller\Api;
use app\common\service\ZipFile;
use think\Db;
use think\Exception;

/**
 * 首页接口use think\Db;
use think\Exception;
 */
class Index extends Api
{
    protected $noNeedLogin = ['index','articleDetail','carLocationList','brandList',
        'bankList','systemNoticeList','helpList','getServicePhone','chargePileSelect','chargePileDetail','warnList','warnLog','img','broad','chargingAddress','chargePileList'];
    protected $noNeedRight = ['uploadInfo','carInfo','getInfo','updateInfo','addCard','cardList',
        'cardDetault','delCard','uploadDegrees','degreesList','billList','noticeList','bindPhone',
        'degreesLists','addChargePile','delChargePile','pileList','uploadDanger'];

    /**
     * 首页
     *
     */
    public function index()
    {
        $banner=Banner::where('status',1)->field('id,image,name,status')->select();
        $news=Article::where('article_category_id',3)->where('status',1)->field('id,name,image,status')->order('createtime desc')->select();
        foreach ($news as &$k){
            $k['image']=$this->request->domain().$k['image'];
        }
        foreach ($banner as &$k){
            $k['image']=$this->request->domain().$k['image'];
        }
        $key=md5(config('site.secret_key'));
        $this->success('成功',compact('banner','news','key'));
    }

    /**
     * 文章详情
     */
    public function articleDetail()
    {
        $id=$this->request->request('id');
        if (empty($id)) $this->error('请上传文章id');
        $info=Article::where('id',$id)->where('status',1)
            ->field('id,name,image,content')
            ->field('FROM_UNIXTIME(createtime,"%Y-%c-%d") as createtime')
            ->find();
        if (!$info) $this->error('该文章已下架');
        $info['image']=$this->request->domain().$info['image'];
        $this->success('成功',$info);
    }

    /**
     * 车辆信息 筛选列表
     */
    public function carLocationList()
    {
        //车牌归属地列表
        $location_list=CarLocation::where('status',1)->field('id,name,status')->select();
        //车辆品牌
        $brand_list=CarBrand::where('status',1)->field('id,name,status')->select();
        //车身颜色
        $color_list=CarColor::where('status',1)->field('id,name,status')->select();
        //电池类型
        $type_list=BatteryType::where('status',1)->field('id,name,status')->select();
        $this->success('成功',compact('location_list','brand_list','color_list','type_list'));
    }

    /**
     * 车辆品牌搜索 及 排序
     */
    public function brandList()
    {
        $search=$this->request->request('search');
        $brand_list=CarBrand::where('status',1);
        if (empty($search)) $brand_list=$brand_list;
        else $brand_list=$brand_list->where('name','like',"%$search%");
        $brand_list=$brand_list->field('id,name,status')->select();
        if (count($brand_list)>0) $list=(new \app\common\service\Common())->chartSort($brand_list,'name');
        else $list=$brand_list;
        $this->success('成功',(object)$list);
    }

    /**
     * 车辆信息上传
     */
    public function uploadInfo()
    {
        $car_location_id=$this->request->request('car_location_id');
        $plate_number=$this->request->request('plate_number');
        $car_brand=$this->request->request('car_brand');
        $car_color=$this->request->request('car_color');
        $car_code=$this->request->request('car_code');
        $car_model=$this->request->request('car_model');
        $manufacturer=$this->request->request('manufacturer');
        $battery_type_id=$this->request->request('battery_type_id');
        $label_one=$this->request->request('label_one');
        $battery_year_one=$this->request->request('battery_year_one');
        $is_reserve=$this->request->request('is_reserve');
        $label_two=$this->request->request('label_two');
        $battery_year_two=$this->request->request('battery_year_two');
        $theft_protection=$this->request->request('theft_protection');
        $insurance=$this->request->request('insurance');
        $car_image=$this->request->request('car_image');
        $qualified_image=$this->request->request('qualified_image');
        if (!isset($car_brand) || empty($car_brand)) $this->error('请填写车辆品牌');
        if (!isset($car_color)|| empty($car_color)) $this->error('请填写车身颜色');
        if (empty($car_code)) $this->error('请输入车辆编码');
        if ($battery_type_id==0) $this->error('请选择电池类型');
        if ($battery_year_one==0) $this->error('请选择电池使用年限');
        if (empty($car_image)) $this->error('请选择上传车身照片');
        if ($is_reserve==1){
            if ($battery_year_two==0) $this->error('请选择备用电池使用年限');
        }
        $data['user_id']=$this->auth->id;
        $data['car_location_id']=$car_location_id;
        $data['plate_number']=$plate_number;
        $data['car_brand']=$car_brand;
        $data['car_color']=$car_color;
        $data['car_code']=$car_code;
        $data['car_model']=$car_model;
        $data['manufacturer']=$manufacturer;
        $data['battery_type_id']=$battery_type_id;
        $data['label_one']=$label_one;
        $data['battery_year_one']=$battery_year_one;
        $data['is_reserve']=$is_reserve;
        $data['label_two']=$label_two;
        $data['battery_year_two']=$battery_year_two;
        $data['theft_protection']=$theft_protection;
        $data['insurance']=$insurance;
        $data['car_image']=$car_image;
        $data['qualified_image']=$qualified_image;
        $data['createtime']=time();
        $res1=CarModel::where('user_id',$this->auth->id)->find();
        if ($res1) $res=CarModel::update($data,['id'=>$res1['id']]);
        else $res=CarModel::create($data);
        if ($res) $this->success('上传成功');
        else $this->error('上传失败');
    }


    /**
     * 查看车辆信息
     */
    public function carInfo()
    {
        $res=CarModel::where('user_id',$this->auth->id)->find();
        if ($res) $this->success('成功',$res);
        else $this->error('失败');
    }



    /**
     * 修改个人信息
     */
    public function updateInfo()
    {
        $avatar=$this->request->request('avatar');
        $nickname=$this->request->request('nickname');
        $mobile=$this->request->request('mobile');
        $address=$this->request->request('address');
        $province=$this->request->request('province');
        $city=$this->request->request('city');
        $area=$this->request->request('area');
        $addData=[];
        if (!empty($avatar)) $addData['avatar']=$avatar;
        if (!empty($nickname)) $addData['nickname']=$nickname;
        if (!empty($mobile)) $addData['mobile']=$mobile;
        if (!empty($address)) $addData['address']=$address;
        if (!empty($province)) $addData['province']=$province;
        if (!empty($city)) $addData['city']=$city;
        if (!empty($area)) $addData['area']=$area;
        if (count($addData)==0){
            $this->error('请上传要修改的信息');
        }else{
            $res=\app\admin\model\User::update($addData,['id'=>$this->auth->id]);
            if ($res) $this->success('修改成功');
            else $this->error('修改失败');
        }
    }

    /**
     * 添加银行卡
     */
    public function addCard()
    {
        $name=$this->request->request('name');
        $mobile=$this->request->request('mobile');
        $bank=$this->request->request('bank_id');
        $card_num=$this->request->request('card_num');
        $is_default=$this->request->request('is_default');
        if (!preg_match("/^1[3456789]\d{9}$/",$mobile)) $this->error('手机号格式错误');
        if (empty($name)) $this->error('请输入持卡人姓名');
        if (empty($bank)) $this->error('请选择开户行');
        if (empty($card_num)) $this->error('请输入卡号');
        $addData['user_id']=$this->auth->id;
        $addData['name']=$name;
        $addData['mobile']=$mobile;
        $addData['bank_id']=$bank;
        $addData['card_num']=$card_num;
        $addData['is_default']=$is_default;
        Db::startTrans();
        try{
            if ($is_default==1){
                BankCard::update(['is_default'=>0],['user_id'=>$this->auth->id]);
            }
            BankCard::create($addData);
            Db::commit();
            $this->success('添加成功');
        }catch (Exception $e){
            $this->error($e->getMessage());
            Db::rollback();
        }
    }

    /**
     * 用户银行卡列表
     */
    public function cardList()
    {
        $res=BankCard::where('user_id',$this->auth->id)->select();
        foreach ($res as $k){
            $k['card_num']=(new \app\common\service\Common())->strreplace($k['card_num'],0,4);
        }
        $this->success('成功',$res);
    }

    /**
     * 设置银行卡为默认
     */

    public function cardDetault()
    {
        $id=$this->request->request('id');
        if (empty($id)) $this->error('请选择银行卡');
        Db::startTrans();
        try{
            BankCard::update(['is_default'=>0],['user_id'=>$this->auth->id]);
            BankCard::update(['is_default'=>1],['id'=>$id]);
            Db::commit();
            $this->success('设置成功');
        }catch (Exception $e){
            $this->error($e->getMessage());
            Db::rollback();
        }
    }

    /**
     * 删除某个银行卡
     */
    public function delCard()
    {
        $id=$this->request->request('id');
        if (empty($id)) $this->error('请选择银行卡');
        $res=BankCard::destroy($id);
        if ($res) $this->success('删除成功');
        else $this->error('删除失败');
    }


    /**
     * 充电桩地址查询
     */
    public function chargingAddress()
    {
        $address_name = $this->request->request('address_names');
        if(!$address_name){
            $this->error('请输入地址名称');
        }
        $result =\app\admin\model\ChargePile::where('province|citys|area|street|community|village|address','like','%'.$address_name.'%')->where('status',1)->field('province,citys,area,street,community,village,address')->select();
        $data=[];
        foreach ($result as $k=>$v){
            $data[$k]['address']=$v['address'];
            $data[$k]['address_name'] = $v['province'].$v['citys'].$v['area'].$v['street'].$v['community'].$v['village'].$v['address'];
        }
        if ($result) $this->success('成功',$data);
        else $this->error('失败');

    }
    /**
     * 充电桩位置列表
     */
    public function chargePileList()
    {
        $address_name = $this->request->request('address_name');
        $list=ChargePile::where('status',1)->where('province|citys|area|street|community|village|address','like','%'.$address_name.'%')->field('id,device_number as name,longitude,latitude,operator_code')->select();
        $this->success('成功',$list);
    }
    /**
     * 充电桩详情
     */
    public function chargePileDetail()
    {
        $id=$this->request->request('id');
        if (!isset($id)) $this->error('请选择充电桩');
        $res=Db::table('yp_charge_pile')->alias('c')
            ->join('manufacturer m','c.manufacturer_id=m.id','LEFT')
            ->where('c.id',$id)
            ->field('c.*,m.name')
            ->find();
        $this->success('成功',$res);
    }

    /**
     * 房东上传用电度数
     */
    public function uploadDegrees()
    {
        $number=$this->request->request('number');
        $img=$this->request->request('image');
        $bank_card_id=$this->request->request('bank_card_id');
        $id=$this->request->request('id');
        if ($number==0) $this->error('请输入用电度数');
        if ($bank_card_id==0) $this->error('请选择银行卡');
        $this_month=date('Y-m-01',strtotime(date('Y-m-d')));
        $last_month=date('Y-m-d',strtotime(date('Y-m-01').'-1 month'));
        $this_one=strtotime($this_month);
        $this_five=strtotime($this_month)+86400*5;
        $last_one=strtotime($last_month);
        $last_five=strtotime($last_month)+86400*5;
        $user_degress=\app\admin\model\User::where('id',$this->auth->id)->value('degree_money');
        $is_last=ElectricDegrees::where('createtime','between',[$last_one,$last_five])->where('user_id',$this->auth->id)->find();
        if ($is_last) $last_num=$is_last['degrees_num'];
        else $last_num=0;
        if ($last_num==0){
            $addData['use_num']=0;
            $addData['money']=0;
        }else{
            $addData['use_num']=bcsub($number,$last_num,2);
            $addData['money']=bcsub($number,$last_num,2)*$user_degress;
        }
        $addData['degrees_num']=$number;
        $addData['image']=$img;
        $addData['user_id']=$this->auth->id;
        $addData['bank_card_id']=$bank_card_id;
        $addData['cause']='';

        if ($id==0){
            $is_upload=ElectricDegrees::where('createtime','between',[$this_one,$this_five])->where('user_id',$this->auth->id)->find();
            if ($is_upload) $this->error('每月只能上传一次');
            $is_fa=ElectricDegrees::where('createtime','between',[$last_one,$last_five])->where('user_id',$this->auth->id)->where('status',0)->find();
            if ($is_fa) $this->error('上月未结算，请勿抄送本月电表');
            $res=ElectricDegrees::create($addData);
        }else{
            $addData['status']=0;
            $res=ElectricDegrees::update($addData,['id'=>$id]);
        }
        if ($res) $this->success('成功');
        else $this->error('失败');
    }


    /**
     * 房东查看已上传电表列表
     */
    public function degreesList()
    {
        $page=$this->request->request('page');
        $limit=$this->request->request('limit');
        $list=Db::table('yp_electric_degrees')->alias('e')
            ->join('bank_card b','e.bank_card_id=b.id','left')
            ->where('e.user_id',$this->auth->id)
            ->where('e.status','in','0,2')
            ->field('e.*,b.card_num')
            ->field('FROM_UNIXTIME(e.createtime,"%Y-%c-%d %H:%i:%s") as createtime')
            ->page($page,$limit)->select();

        foreach ($list as $k=>&$v){
            $v['card_num']=(new \app\common\service\Common())->strreplace($v['card_num'],0,4);
        }

        $count=ElectricDegrees::where('user_id',$this->auth->id)->where('status','in','0,2')
            ->count();
        $this->success('成功',compact('list','count'));
    }

    /**
     * 房东查看已结算电表列表
     */
    public function degreesLists()
    {
        $page=$this->request->request('page');
        $limit=$this->request->request('limit');
        $list=Db::table('yp_electric_degrees')->alias('e')
            ->join('bank_card b','e.bank_card_id=b.id','left')
            ->where('e.user_id',$this->auth->id)
            ->where('e.status','=','1')
            ->field('e.*,b.card_num')
            ->field('FROM_UNIXTIME(e.createtime,"%Y-%c-%d %H:%i:%s") as createtime')
            ->page($page,$limit)->select();

        foreach ($list as $k=>&$v){
            $v['card_num']=(new \app\common\service\Common())->strreplace($v['card_num'],0,4);
        }

        $count=ElectricDegrees::where('user_id',$this->auth->id)->where('status','=','1')->count();
        $this->success('成功',compact('list','count'));
    }

    /**
     * 银行列表
     */
    public function bankList()
    {
        $list=Bank::where('status',1)->select();
        $this->success('成功',$list);
    }

    /**
     * 查看消费记录
     */
    public function billList()
    {
        $page=$this->request->request('page');
        $limit=$this->request->request('limit');
        $list=Db::table('yp_bill_order')->alias('b')
            ->join('manufacturer m','b.manufacturer_id=m.id','left')
            ->where('b.user_id',$this->auth->id)
            ->field('b.*,m.name')
            ->field('FROM_UNIXTIME(b.createtime,"%Y-%c-%d %H:%i:%s") as createtime')
            ->field('FROM_UNIXTIME(b.paytime,"%Y-%c-%d %H:%i:%s") as paytime')
            ->field('FROM_UNIXTIME(b.refund_time,"%Y-%c-%d %H:%i:%s") as refund_time')
            ->page($page,$limit)->select();
        $count=BillOrder::where('user_id',$this->auth->id)->count();
        $this->success('成功',compact('count','list'));
    }

    /**
     * 通知消息列表
     */
    public function noticeList()
    {
        $page=$this->request->request('page');
        $limit=$this->request->request('limit');
        $noticeList=UserMessage::where('user_id',$this->auth->id)->page($page,$limit)->order('createtime desc')->select();
        $count=UserMessage::where('user_id',$this->auth->id)->count();
        $this->success('成功',compact('noticeList','count'));
    }

    /**
     * 系统消息列表
     */
    public function systemNoticeList()
    {
        $page=$this->request->request('page');
        $limit=$this->request->request('limit');
        $systemList=Article::where('article_category_id',2)->where('status',1)->page($page,$limit)->order('createtime desc')->select();
        $count=Article::where('article_category_id',2)->where('status',1)->count();
        $this->success('成功',compact('systemList','count'));
    }


    /**
     * 绑定手机号
     */
    public function bindPhone()
    {
        $phone=$this->request->request('phone');
        if (!preg_match("/^1[3456789]\d{9}$/",$phone)) $this->error('手机号格式错误');
        $res=\app\admin\model\User::update(['mobile'=>$phone],['id'=>$this->auth->id]);
        if ($res) $this->success('成功');
        else $this->error('失败');
    }

    /**
     * 帮助中心
     */
    public function helpList()
    {
        $page=$this->request->request('page');
        $limit=$this->request->request('limit');
        $systemList=Article::where('article_category_id',4)->where('status',1)->page($page,$limit)->select();
        $count=Article::where('article_category_id',4)->where('status',1)->count();
        $this->success('成功',compact('systemList','count'));
    }

    /**
     * 客服电话
     */
    public function getServicePhone()
    {
        $phone=config('site.service_phone');
        $this->success('成功',$phone);
    }

    /**
     * 添加充电桩
     */
    public function addChargePile()
    {
        $device_number=$this->request->request('device_number');
        $manufacturer_id=$this->request->request('manufacturer_id');
        $operator_id=$this->request->request('operator_id');
        $operator_code=$this->request->request('operator_code');
        $kind_id=$this->request->request('kind_id');
        $street=$this->request->request('street');
        $community=$this->request->request('community');
        $village=$this->request->request('village');
        $address=$this->request->request('address');
        $city=$this->request->request('city');
        $longitude=$this->request->request('longitude');
        $latitude=$this->request->request('latitude');
        $port=$this->request->request('port');
        $installtime=$this->request->request('installtime');
        $meter_code=$this->request->request('meter_code');
        $unit_type=$this->request->request('unit_type');
        $powers=$this->request->request('powers');
        $install_way=$this->request->request('install_way');
        $recharge_way=$this->request->request('recharge_way');
        $images=$this->request->request('images');
        $files=$this->request->request('files');
        if (empty($device_number)||empty($manufacturer_id)||empty($operator_id)||
            empty($operator_code)||empty($kind_id)||empty($street)||empty($community)||
            empty($village)||empty($address)||empty($city)||empty($longitude)||empty($latitude)||
            empty($port) ||empty($installtime) || empty($meter_code || empty($images) || empty($files))
        ) $this->error('请填写必填项');
        $citys=explode('/',$city);
        $addData['device_number']=$device_number;
        $addData['manufacturer_id']=$manufacturer_id;
        $addData['operator_id']=$operator_id;
        $addData['operator_code']=$operator_code;
        $addData['kind_id']=$kind_id;
        $addData['street']=$street;
        $addData['community']=$community;
        $addData['village']=$village;
        $addData['address']=$address;
        $addData['city']=$city;
        $addData['province']=$citys[0];
        $addData['citys']=$citys[1];
        $addData['area']=$citys[2];
        $addData['longitude']=$longitude;
        $addData['latitude']=$latitude;
        $addData['port']=$port;
        $addData['installtime']=strtotime($installtime);
        $addData['meter_code']=$meter_code;
        $addData['user_id']=$this->auth->id;
        $addData['createtime']=time();
        $addData['images']=$images;
        $addData['files']=$files;
        $addData['unit_type']=$unit_type;
        $addData['powers']=$powers;
        $addData['install_way']=$install_way;
        $addData['recharge_way']=$recharge_way;
        $res=ChargePile::create($addData);
        if ($res) $this->success('成功');
        else $this->error('失败');
    }

    /**
     * 填写充电桩的筛选列表
     */
    public function chargePileSelect()
    {
        //运营商列表
        $operator_list=Operator::where('status',1)->field('id,operator_name,operator_code')->select();
        //种类列表
        $kind_list=Kind::where('status',1)->field('id,kind_name')->select();
        //品牌列表
        $manufacturer_list=Manufacturer::where('status',1)->field('id,name')->select();
        $this->success('成功',compact('operator_list','kind_list','manufacturer_list'));
    }

    /**
     * 删除充电桩
     */
    public function delChargePile()
    {
        $id=$this->request->request('id');
        $res=ChargePile::destroy($id);
        if ($res) $this->success('成功');
        else $this->error('失败');
    }

    /**
     * 充电桩列表
     */
    public function pileList()
    {
        $list=Db::table('yp_charge_pile')->alias('cp')
            ->join('operator o','cp.operator_id=o.id','left')
            ->join('manufacturer m','cp.manufacturer_id=m.id','left')
            ->join('kind k','cp.kind_id=k.id','left')
            ->where('cp.status',1)
            ->where('cp.user_id',$this->auth->id)
            ->field('cp.*,o.operator_name,m.name manufacturer_name,k.kind_name')
            ->field('FROM_UNIXTIME(cp.installtime,"%Y-%c-%d") as installtime')
            ->order('createtime desc')
            ->select();
        $this->success('成功',$list);
    }

    /**
     * 预警设备列表
     */
    public function warnList()
    {
//        $uid=45;
        $uid=$this->auth->id;
        $warn_area=\app\admin\model\User::where('id',$uid)->value('warn_district');
        $warn_area=explode("\r\n",$warn_area);
        $list=WarningFacility::where('status',1)->where('street','in',$warn_area)->where('user_id',$uid)->field('id,device_number as name,longitude,latitude')->select();
        $this->success('成功',$list);
    }

    /**
     * 预警记录
     */
    public function warnLog()
    {
        $id=$this->request->request('device_number');
        $page=$this->request->request('page');
        $limit=$this->request->request('limit');
        $list=WarningLog::where('device_number',$id)->order('createtime desc')->page($page,$limit)->select();
        foreach ($list as $v){
            $v['createtime']=date('Y-m-d H:m:s',$v['createtime']);
        }
        $total=WarningLog::where('device_number',$id)->count();
        $this->success('成功',compact('list','total'));
    }

    public function img()
    {
        $config = get_addon_config('alioss');
        $list=Db::table('yp_charge_pile')
                ->where('images','neq','')
                ->field('images,id')
                ->select();

        foreach ($list as $k=>&$v){
            $v['img']=explode(',',$v['images']);
            $v['a']=[];
           foreach ($v['img'] as $k1){
               $res=parse_url($k1);
               array_push($v['a'],$res['path'].'?x-oss-process=image/resize,p_10');
           }
           $v['images']=implode(',',$v['a']);
           unset($v['img']);
           unset($v['a']);
        }
//        (new \app\admin\model\User())->saveAll($list);

        $this->success('s',$config);
    }

    /**
     * 宽带信息提交
     */
    public function broad()
    {
        $name=$this->request->post('name','');
        $mobile=$this->request->post('mobile','');
        $address=$this->request->post('address','');
        $place=$this->request->post('place','');
        if (empty($name)||empty($mobile)||empty($address)) $this->error('请填写必填项！');
        $data['name']=$name;
        $data['mobile']=$mobile;
        $data['address']=$address;
        $data['place']=$place;
        $data['status']=1;
        $data['createtime']=time();
        $res=\app\admin\model\Broad::create($data);
        if ($res) $this->success('提交成功');
        else $this->error('提交失败');
    }

    /**
     * 隐患提交
     *
     * longitude 经度
     * latitude 纬度
     * images 图片
     * info  描述
     */
    public function uploadDanger()
    {
        $uid=$this->auth->id;
        $longitude=$this->request->request('longitude','');
        $latitude=$this->request->request('latitude','');
        $images=$this->request->request('images','');
        $info=$this->request->request('info','');
        $address=$this->request->request('address','');
        if (empty($longitude)||empty($latitude)||empty($images)||empty($info)||empty($address)) $this->error('缺少必传参数');
        $data['longitude']=$longitude;
        $data['latitude']=$latitude;
        $data['images']=$images;
        $data['user_id']=$uid;
        $data['info']=$info;
        $data['address']=$address;
        $data['createtime']=time();
        $res=HiddenDanger::create($data);
        if ($res) $this->success('成功');
        else $this->error('失败');
    }

}
